//
//  SEHospitalizeViewModel.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/15.
//

import UIKit

class SEHospitalizeViewModel: SEBaseViewModel {
    private let loadHomeDataQueue = DispatchQueue(label: "loadHomeData", attributes: .concurrent)
    private let loadHomeDataGroup = DispatchGroup()

    var hospitalListViewModel = SEHospitalListViewModel(hospitalListType: .examine, withLoading: false)

    var scanHospitalViewModel = SEHospitalListViewModel(hospitalListType: .examine, withLoading: true)

    var scanHospitalHandler: ((SEHttpStatus) -> Void)?

    var scanDoctorViewModel = SEDoctorDetailViewModel()

    var scanDoctorHandler: ((SEHttpStatus) -> Void)?

    var hospitalList: [SEHospitalListItem] {
        return hospitalListViewModel.models
    }
    var departmentList: [SEDepartmentItem] = []

    var status: SEHttpStatus = .success

    var locationRegion: String = "打开定位"

    var headlineModels: [SEHospitalizeHeadlinesCellModel] {
        return [
            SEHospitalizeHeadlinesCellModel(title: "EYE·科普丨家有高血压患者请注意！这件事你知道吗？",
                                            image:  Asset.headlineOneImage.image,
                                            url: URL(string: "https://mp.weixin.qq.com/s/xFDk89n550xg_M6TmXKm5A")),
            SEHospitalizeHeadlinesCellModel(title: "EYE·科普丨“针”是小心“眼”——得了麦粒肿是一种什么样的体验？",
                                            image: Asset.headlineTwoImage.image,
                                            url: URL(string: "https://mp.weixin.qq.com/s/GXofQvj0gJuKLfvoFfnMJg")),
            SEHospitalizeHeadlinesCellModel(title: "EYE·科普 | 上班族如何呵护眼睛这扇心灵之窗",
                                            image: Asset.headlineThreeImage.image,
                                            url: URL(string: "https://mp.weixin.qq.com/s/nlb96PuaxmeHC6KSd8vhhg"))
        ]
    }

    func headlineModel(indexPath: IndexPath) -> SEHospitalizeHeadlinesCellModel {
        return headlineModels[indexPath.row]
    }

    var numberOfSections: Int { 3 }
    
    func numberOfRows(in section: Int) -> Int {
        let sectionType = SEHospitalizeSection(rawValue: section) ?? .unknown
        switch sectionType {
        case .location:  return 1
        case .service:   return 1
        case .headlines: return headlineModels.count
        default:         return 0
        }
    }
    
    var numberOfLocationRows: Int { hospitalList.count > 3 ? 3 : hospitalList.count }
    
    private var _cellHeight: CGFloat = 0.0
    var cellHeight: CGFloat {
        get { _cellHeight }
        set { _cellHeight = newValue }
    }
    
    func collectionViewCellHeight(collectionView: UICollectionView, indexPath: IndexPath) {
        guard let frame = collectionView.collectionViewLayout.layoutAttributesForItem(at: indexPath)?.frame else { return }
        cellHeight = 80 + frame.maxY
    }
    
    // MARK: - 专科服务
    
    var numberOfServiceItems: Int {
        return departmentList.count > 6 ? 6 : departmentList.count
    }
    
    func serviceCellViewModel(at indexPath: IndexPath) -> SEDepartmentItemViewModel {
        return SEDepartmentItemViewModel(model: departmentList[indexPath.item])
    }
    
    // MARK: - load data
    
    func requestHomeData() {
        loadHomeDataGroup.enter()
        loadHomeDataQueue.async { [weak self] in
            self?.getListOfDepartments()
        }

        loadHomeDataGroup.enter()
        loadHomeDataQueue.async { [weak self] in
            self?.getHospitalList()
        }
        
        loadHomeDataGroup.notify(queue: DispatchQueue.main) { [weak self] in
            guard let self = self else { return }
            self.updateData?(self.status)
        }
    }
    
    private func getListOfDepartments() {
        SEHttpManager.shared.requestForModelArray(SEDepartmentAPI.listOfAllDepartments, model: SEDepartmentItem.self, withLoading: withLoading) { (models, httpStatus) in
            self.status = httpStatus
            self.loadHomeDataGroup.leave()
            switch httpStatus {
            case .success:
                self.departmentList = models ?? []
            case .auth: break
            case .failure(let message):
                SEHUD.showError(message: message)
            }
        }
    }

    private func getHospitalList() {
        hospitalListViewModel.requestHospitalList()
        hospitalListViewModel.updateData = { httpStatus in
            self.status = httpStatus
            self.loadHomeDataGroup.leave()
        }
    }

    func scanGetHospitalList() {
        scanHospitalViewModel.requestHospitalList()
        scanHospitalViewModel.updateData = { status in
            self.scanHospitalHandler?(status)
        }
    }

    func scanGetDoctorDetail() {
        scanDoctorViewModel.getDoctorDetailInfo()
        scanDoctorViewModel.updateData = {status in
            self.scanDoctorHandler?(status)
        }
    }
}
